<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Product;

use Tymon\JWTAuth\Contracts\JWTSubject;

class Users extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * 放行白名单字段 ，放行的字段才能写入
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'phone'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * 用户收货地址列表
     */
    public function MemberAddress()
    {
        return $this->hasMany('App\Models\MemberAddress','user_id');
    }

    /**
     * 购物车与用户关联关系
     */
    public function cartItems()
    {
        return $this->hasMany(CartItem::class,'user_id');
    }

     /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     *  商品收藏多对多关联
     */
    public function favoriteProducts()
    {
        /**
         * Define a many-to-many relationship.
         *
         * @param  string  $related 最终获取数据的关联表
         * @param  string  $table 中间表
         * @param  string  $foreignPivotKey 外键id
         */
        return $this->belongsToMany(Product::class,'user_favorite_products','user_id')->withTimestamps()
            ->orderBy('user_favorite_products.created_at','desc');
    }

    public function FindMemberFirst($data)
    {
        $exist = self::where(['name'=>$data['name']])->count();
        if($exist>0){
            return 1;
        }
        return 0;
    }

    // contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods

    // 必须 声明 接口中那两个方法
    // namespace Tymon\JWTAuth\Contracts;
    // interface JWTSubject


    public function getJWTCustomClaims()
    {
        return [];
    }

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
}
